import { ref } from 'vue';
import { defineStore } from 'pinia';
import { login, logout } from '@/utils/auth';

const useLoginState = defineStore('loginState', () => {
  const username = ref('');
  const isLogin = ref(false); // 登录状态

  async function doLogin(userinfo) {
    try {
      const resp = await login(userinfo.username, userinfo.password);
      if (resp.code === 200) {
        const token = resp.data;
        localStorage.setItem('access-token', token);
        username.value = userinfo.username;
        isLogin.value = true;
        return Promise.resolve(resp);
      }
      // 抛出包含响应信息的错误
      return Promise.reject({ 
        code: resp.code,
        message: resp.msg || '登录失败',
        response: resp
      });
    } catch (error) {
      console.error('登录失败:', error);
      return Promise.reject(error);
    }
  }

  async function doLogout() {
    try {
      const resp = await logout();
      localStorage.removeItem('access-token');
      username.value = '';
      isLogin.value = false;
      return new Promise((resovel, reject) => resovel(resp));
    } catch (error) {
      console.error('登出失败:', error);
      return new Promise((resovel, reject) => reject(error));
    }
  }
  
  return { username, isLogin, doLogin, doLogout };
})

export default useLoginState
